package com.cenntro.oss.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.curator.shaded.com.google.common.collect.Lists;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.cenntro.common.base.BaseServiceImpl;
import com.cenntro.common.exception.BizException;
import com.cenntro.common.mapper.SysconfMapper;
import com.cenntro.common.model.dbo.SysconfDO;
import com.cenntro.common.redis.IRedisService;
import com.cenntro.common.util.ConvertorUtils;
import com.cenntro.common.util.NumUtil;
import com.cenntro.common.util.result.Result;
import com.cenntro.oss.mapper.DevCarMapper;
import com.cenntro.oss.mapper.DevDeviceOnlineMapper;
import com.cenntro.oss.mapper.DevDeviceStaticMapper;
import com.cenntro.oss.mapper.DevFollowMapper;
import com.cenntro.oss.mapper.DevOperateMapper;
import com.cenntro.oss.mapper.DevRunMapper;
import com.cenntro.oss.model.dbo.DevCarDO;
import com.cenntro.oss.model.dbo.DevDeviceOnlineDO;
import com.cenntro.oss.model.dbo.DevDeviceStaticDO;
import com.cenntro.oss.model.dbo.DevFollowDO;
import com.cenntro.oss.model.dbo.DevSupplyImeiDO;
import com.cenntro.oss.model.dbo.DeviceListDO;
import com.cenntro.oss.model.dbo.SysAgentDO;
import com.cenntro.oss.model.qo.DevListQO;
import com.cenntro.oss.model.qo.DeviceCarListMapQO;
import com.cenntro.oss.model.qo.DeviceListQO;
import com.cenntro.oss.model.vo.DeivceDetailsVO;
import com.cenntro.oss.model.vo.DeivceListVO;
import com.cenntro.oss.model.vo.DeviceCarListMapVO;
import com.cenntro.oss.model.vo.DeviceDataCountVO;
import com.cenntro.oss.model.vo.DeviceListVO;
import com.cenntro.oss.model.vo.DeviceStaticVO;
import com.cenntro.oss.model.vo.VehicleDetailVO;
import com.cenntro.oss.model.vo.VehicleInsertVO;
import com.cenntro.oss.model.vo.VehicleVO;
import com.cenntro.oss.service.DevCarService;
import com.cenntro.oss.service.DevDeviceOnlineService;
import com.cenntro.oss.service.DevDeviceStaticService;
import com.cenntro.oss.service.DevPartitionExtService;
import com.cenntro.oss.service.DevSupplyImeiService;
import com.cenntro.oss.service.SysAgentService;
import com.cenntro.repair.mapper.AfterRepairFormMapper;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

/**
 * <p>
 * 车辆配置信息，静态数据表 服务实现类
 * </p>
 *
 * @author
 * @since 2018-09-13
 */
@Service
public class DevDeviceStaticServiceImpl extends BaseServiceImpl<DevDeviceStaticMapper>
        implements DevDeviceStaticService {

    @Resource
    private DevFollowMapper devFollowMapper;

    @Resource
    private DevCarMapper devCarMapper;

    @Resource
    private DevRunMapper devRunMapper;

    @Resource
    private DevOperateMapper devOperateMapper;

    @Resource
    private DevDeviceOnlineService devDeviceOnlineService;

    @Resource
    // 测试添加
    private DevDeviceStaticService devDeviceStaticService;

    @Resource
    private IRedisService redisService;

    //
    // @Resource
    // private MQProducerSendMsgProcessor producer;
    @Resource
    private SysAgentService sysAgentService;

    @Resource
    private DevCarService devCarService;

    @Resource
    private SysconfMapper sysconfMapper;

    @Resource
    private DevSupplyImeiService supplyImeiService;

    @Resource
    private DevDeviceStaticMapper devDeviceStaticMapper;

    @Resource
    private DevDeviceOnlineMapper devDeviceOnlineMapper;

    @Resource
    private DevPartitionExtService DevPartitionExtService;

    @Resource
    private AfterRepairFormMapper afterRepairFormMapper;

    @Override
    public List<DeivceListVO> staticAndOnlineAndCarList(DeviceListQO qo) {
        return devDeviceStaticMapper.staticAndOnlineAndCarList(qo);
    }

    @Override
    public DeivceDetailsVO devDetail(Integer devId) {
        int count = afterRepairFormMapper.selectCount(ImmutableMap.of("devId", devId));
        DeivceDetailsVO detailsVO = devDeviceStaticMapper.devDetail(devId);
        detailsVO.setRepairCount(count);
        DevCarDO Car = devCarMapper.selectById(detailsVO.getCarId());
        Integer haveKM = Integer.valueOf(Car.getLife() * detailsVO.getBattery() / 100 - 5);
        detailsVO.setHaveKM(haveKM <= 0 ? 0 : haveKM);
        DevFollowDO follow = devFollowMapper.selectOne(ImmutableMap.of("devId", devId));
        detailsVO.setIsFollow(follow == null ? 0 : 1);
        detailsVO.setLongIsFull((100 - detailsVO.getBattery()) * longFull / 100);
        return detailsVO;
    }

    @Override
    public List<Object> selectPage(Object t) {
        VehicleVO vo = (VehicleVO) t;
        DevDeviceStaticDO dsd = new DevDeviceStaticDO();
        dsd.setStatus(vo.getStatus());
        dsd.setVin(vo.getVin());
        dsd.setAgentId(vo.getAgentId());
        dsd.setParts(vo.getParts());
        dsd.setSort(" convert(carno using gbk) collate gbk_chinese_ci asc");
        //
        List<DevDeviceStaticDO> list = super.selectPage(dsd);
        Set<Integer> carIds = Sets.newHashSet();
        Set<Integer> agentIds = Sets.newHashSet();
        Set<Integer> devIds = Sets.newHashSet();
        for (DevDeviceStaticDO dsddo : list) {
            carIds.add(dsddo.getCarId());
            agentIds.add(dsddo.getAgentId());
            devIds.add(dsddo.getDevId());
        }
        Map<String, Object> param = Maps.newHashMap();
        param.put("devIds", Lists.newArrayList(devIds));
        if (CollectionUtils.isNotEmpty(devIds)) {
            List<DevDeviceOnlineDO> dodList = devDeviceOnlineService.selectByMap(param);
            param.clear();
            param.put("agentIds", agentIds);
            List<SysAgentDO> agentList = sysAgentService.selectByMap(param);
            param.clear();
            param.put("carIds", carIds);
            List<DevCarDO> devcarList = devCarService.selectByMap(param);
            return Lists.newArrayList(this.translate(list, dodList, devcarList, agentList));
        }
        return null;
    }

    @Transactional(rollbackFor = { Exception.class })
    public int update(Object t) {
        DevDeviceStaticDO par = (DevDeviceStaticDO) t;
        DevDeviceStaticDO st = (DevDeviceStaticDO) super.selectById(par.getDevId());
        Map<String, Object> map = Maps.newHashMap();
        if (StringUtils.isNotBlank(par.getCarNo())) {
            map.clear();
            map.put("carNo", par.getCarNo());
            DevDeviceStaticDO temp = (DevDeviceStaticDO) super.selectOne(map);
            if (temp != null) {
                Assert.isTrue((temp != null) && (temp.getDevId().equals(st.getDevId())), "车牌已经被使用");
            }
        }
        if (StringUtils.isNotBlank(par.getImei())) {
            map.clear();
            map.put("imei", par.getImei());
            DevDeviceStaticDO temp = (DevDeviceStaticDO) super.selectOne(map);
            if (temp != null) {
                Assert.isTrue((temp != null) && (temp.getDevId().equals(st.getDevId())), "imei已经被使用");
            }
        }
        if (StringUtils.isNotBlank(par.getVin())) {
            map.clear();
            map.put("vin", par.getVin());
            DevDeviceStaticDO temp = (DevDeviceStaticDO) super.selectOne(map);
            if (temp != null) {
                Assert.isTrue((temp != null) && (temp.getDevId().equals(st.getDevId())), "车架号已经被使用");
            }
        }
        if (st.getAgentId() != null) {
            if (par.getAgentId() == null) {
                if (st.getAgentId() != null) {
                    SysAgentDO sysAgent = (SysAgentDO) this.sysAgentService.selectById(st.getAgentId());
                    sysAgent.setCarNum(Integer.valueOf(NumUtil.toInt(sysAgent.getCarNum(), new Integer[0]) - 1));
                    this.sysAgentService.update(sysAgent);
                    par.setAgentId(null);
                    par.setAgentPath(" ");
                    // par.setUserId(Integer.valueOf(0));
                    // par.setUserPath(" ");
                }
            } else if (!st.getAgentId().equals(par.getAgentId())) {
                SysAgentDO sysAgent = (SysAgentDO) this.sysAgentService.selectById(st.getAgentId());
                sysAgent.setCarNum(Integer.valueOf(NumUtil.toInt(sysAgent.getCarNum(), new Integer[0]) - 1));
                this.sysAgentService.update(sysAgent);
                sysAgent = (SysAgentDO) this.sysAgentService.selectById(par.getAgentId());
                sysAgent.setCarNum(Integer.valueOf(NumUtil.toInt(sysAgent.getCarNum(), new Integer[0]) + 1));
                this.sysAgentService.update(sysAgent);
                par.setAgentId(par.getAgentId());
                par.setAgentPath(" ");
                // par.setUserId(Integer.valueOf(0));
                // par.setUserPath(" ");
            }
        } else if (par.getAgentId() != null) {
            SysAgentDO sysAgent = (SysAgentDO) this.sysAgentService.selectById(st.getAgentId());
            sysAgent = (SysAgentDO) this.sysAgentService.selectById(par.getAgentId());
            sysAgent.setCarNum(Integer.valueOf(NumUtil.toInt(sysAgent.getCarNum(), new Integer[0]) + 1));
            this.sysAgentService.update(sysAgent);
            par.setAgentId(par.getAgentId());
        }
        int count = super.update(par);
        if ((StringUtils.isNotBlank(par.getImei())) && (!st.getImei().equals(par.getImei()))) {
            DevSupplyImeiDO imei = new DevSupplyImeiDO();
            imei.setAllotion(Integer.valueOf(0));
            imei.setImei(st.getImei());
            this.supplyImeiService.updateByImei(imei);
            imei = new DevSupplyImeiDO();
            imei.setAllotion(Integer.valueOf(1));
            imei.setImei(par.getImei());
            this.supplyImeiService.updateByImei(imei);
            // DevPartitionExtService.deleteById(par.getAgentId());
            // DevPartitionExtService.selectPartitionNum(devId);
            // this.producer.send(TopicEnum.VEHICLE_DELETE, null, st.getImei(),
            // st.getImei());
        }
        return count;
    }

    @Transactional(rollbackFor = { Exception.class })
    public int insert(Object t) {
        VehicleInsertVO vo = (VehicleInsertVO) t;
        Map<String, Object> map = Maps.newHashMap();
        map.put("imei", vo.getImei());
        DevDeviceStaticDO dsd = (DevDeviceStaticDO) super.selectOne(map);
        Assert.isTrue(dsd == null, "imei已经被使用");
        map.clear();
        map.put("vin", vo.getVin());
        dsd = (DevDeviceStaticDO) super.selectOne(map);
        Assert.isTrue(dsd == null, "车架号已经被使用");
        if (StringUtils.isNotBlank(vo.getCarNo())) {
            map.clear();
            map.put("carNo", vo.getCarNo());
            dsd = (DevDeviceStaticDO) super.selectOne(map);
            Assert.isTrue(dsd == null, "车牌已经被使用");
        }
        if (StringUtils.isNotBlank(vo.getCarNo())) {
            map.clear();
            map.put("carNo", vo.getCarNo());
            DevDeviceStaticDO temp = (DevDeviceStaticDO) super.selectOne(map);
            Assert.isTrue(temp == null, "车牌已经被使用");
        }
        DevDeviceOnlineDO dod = (DevDeviceOnlineDO) ConvertorUtils.deepConvert(vo, DevDeviceOnlineDO.class);
        // dod.setVincode(vo.getImei());
        dod.setDeviceStatus(Integer.valueOf(0));
        dod.setCity(null);
        dod.setCreateTime(new Date());
        dsd = (DevDeviceStaticDO) ConvertorUtils.deepConvert(vo, DevDeviceStaticDO.class);
        // dsd.setVincode(vo.getImei());
        dsd.setCdt(new Date());
        DevSupplyImeiDO imei = new DevSupplyImeiDO();
        imei.setAllotion(Integer.valueOf(1));
        imei.setImei(vo.getImei());
        this.supplyImeiService.updateByImei(imei);
        if (vo.getAgentId() != null) {
            SysAgentDO sysAgent = (SysAgentDO) this.sysAgentService.selectById(vo.getAgentId());
            sysAgent.setCarNum(Integer.valueOf(NumUtil.toInt(sysAgent.getCarNum(), new Integer[0]) + 1));
            this.sysAgentService.update(sysAgent);
        }
        // dsd.setManageId(Integer.valueOf(8));
        dsd.setStatus(1);
        super.insert(dsd);
        dod.setDevId(dsd.getDevId());
        this.devDeviceOnlineService.insert(dod);
        DevPartitionExtService.selectPartitionNum(dsd.getDevId());
        // this.producer.send(TopicEnum.VEHICLE_ADD, null, dsd.getImei(),
        // dsd.getImei());
        return 0;
    }

    /**
     * 转换VehicleDetailVO
     */
    public List<VehicleDetailVO> translate(List<DevDeviceStaticDO> list, List<DevDeviceOnlineDO> dodList,
            List<DevCarDO> devcarList, List<SysAgentDO> agentList) {
        Map<Integer, DevCarDO> carMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(devcarList)) {
            for (DevCarDO car : devcarList) {
                carMap.put(car.getId(), car);
            }
        }
        Map<Integer, SysAgentDO> agentMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(agentList)) {
            for (SysAgentDO agent : agentList) {
                if (agent != null) {
                    agentMap.put(agent.getId(), agent);
                }
            }
        }
        Map<String, Object> map = Maps.newHashMap();
        map.put("code", "color");
        map.put("status", 1);
        SysconfDO sysconf = new SysconfDO();
        sysconf.setCode("color");
        List<SysconfDO> sysconfList = sysconfMapper.selectPage(sysconf);
        List<VehicleDetailVO> details = Lists.newArrayList();
        A: for (DevDeviceStaticDO dsd : list) {
            for (DevDeviceOnlineDO dod : dodList) {
                if (dsd.getDevId().equals(dod.getDevId())) {
                    VehicleDetailVO vehicle = new VehicleDetailVO();
                    vehicle.setDevId(dsd.getDevId());
                    vehicle.setAgentId(dsd.getAgentId());
                    vehicle.setImei(dsd.getImei());
                    vehicle.setCarNo(dsd.getCarNo());
                    vehicle.setCarNickName(dsd.getCarNickName());
                    vehicle.setCarNub(dsd.getVin());
                    vehicle.setBuyTime(dsd.getBuyTime());
                    vehicle.setBuildTime(dsd.getBuildTime());
                    vehicle.setSaleArea(StringUtils.defaultString(dsd.getSaleCountry()) + " "
                            + StringUtils.defaultString(dsd.getSaleCity()));
                    vehicle.setSaleCountry(dsd.getSaleCountry());
                    vehicle.setSaleCity(dsd.getSaleCity());
                    vehicle.setParts(dsd.getParts());
                    vehicle.setSendTime(dsd.getSendTime());
                    vehicle.setColor(getColorName(sysconfList, dsd.getColor()));
                    SysAgentDO agent = agentMap.get(dsd.getAgentId());
                    if (agent != null) {
                        vehicle.setCompany(agent.getCompany());
                        vehicle.setLinkTel(agent.getLinkTel());
                    }
                    // DevCarDO
                    DevCarDO car = carMap.get(dsd.getCarId());
                    if (car != null) {
                        vehicle.setCarType(car.getTitle());
                        vehicle.setChargeLong(car.getChargeLong());
                        vehicle.setVolume(car.getVolume());
                        vehicle.setLength(car.getLength());
                        vehicle.setModels(car.getModels());
                        vehicle.setLoadLength(car.getLoadLength());
                        vehicle.setLoadHeight(car.getLoadHeight());
                        vehicle.setPower(car.getPower());
                        vehicle.setBatteryCapacity(car.getBattery());
                        vehicle.setLife(car.getLife());
                        vehicle.setCarType(car.getTitle());
                    }
                    // dod
                    vehicle.setAddress(StringUtils.defaultString(dod.getCity()) + " "
                            + StringUtils.defaultString(dod.getAddress()));
                    vehicle.setLastUpTime(dod.getLastUpTime());
                    vehicle.setFire(dod.getFire());
                    vehicle.setDoor(dod.getDoor());
                    vehicle.setSpeed(dod.getSpeed());
                    vehicle.setLat(dod.getLat());
                    vehicle.setLng(dod.getLng());
                    vehicle.setCity(dod.getCity());
                    vehicle.setBattery(dod.getBattery());
                    vehicle.setBms(dod.getBms());
                    vehicle.setDeviceStatus(dod.getDeviceStatus());
                    if (dod.getDeviceStatus().equals(1)) {
                        vehicle.setDeviceStatus(5);
                    }
                    vehicle.setToDir(dod.getToDir());
                    vehicle.setFarAway(dod.getFarAway());
                    details.add(vehicle);
                    continue A;
                }
            }
        }
        return details;
    }

    @Override
    public Result assign(List<Integer> Ids, Integer agentId) {
        DevDeviceStaticDO dsd = new DevDeviceStaticDO();
        for (Integer Id : Ids) {
            dsd.setDevId(Id);
            dsd.setAgentId(agentId);
            this.update(dsd);
        }
        return Result.ok();
    }

    private String getColorName(List<SysconfDO> sysconfList, String value) {
        if (StringUtils.isBlank(value)) {
            return "";
        }
        for (SysconfDO sysconf : sysconfList) {
            if (value.equals(sysconf.getValue())) {
                return sysconf.getName();
            }
        }
        return "";
    }

    @Transactional(rollbackFor = { Exception.class })
    public int deleteById(Integer Id) {
        DevDeviceStaticDO dsd = (DevDeviceStaticDO) super.selectById(Id);
        String oldImei = dsd.getImei();
        if (dsd != null) {
            DevDeviceOnlineDO dod = (DevDeviceOnlineDO) this.devDeviceOnlineService
                    .selectOne(ImmutableMap.of("devId", dsd.getDevId()));
            if (dod != null) {
                String imei = StringUtils.defaultString(dsd.getImei()) + "-"
                        + String.format("%04d", new Object[] { Integer.valueOf(RandomUtils.nextInt(0, 1000)) });
                dod.setDeviceStatus(Integer.valueOf(-1));
                this.devDeviceOnlineService.update(dod);
                dsd.setStatus(Integer.valueOf(-1));
                dsd.setImei(imei);
                super.update(dsd);
                if (dsd.getAgentId() != null) {
                    SysAgentDO sysAgent = (SysAgentDO) this.sysAgentService.selectById(dsd.getAgentId());
                    sysAgent.setCarNum(Integer.valueOf(NumUtil.toInt(sysAgent.getCarNum(), new Integer[0]) - 1));
                    this.sysAgentService.update(sysAgent);
                }
                DevSupplyImeiDO supplyImei = new DevSupplyImeiDO();
                supplyImei.setAllotion(Integer.valueOf(0));
                supplyImei.setImei(oldImei);
                this.supplyImeiService.updateByImei(supplyImei);
                DevPartitionExtService.deleteByDevId(Id);
                // this.producer.send(TopicEnum.VEHICLE_DELETE, null, oldImei,
                // oldImei);
                return 1;
            }
        }
        return 0;
    }

    /**
     * 分配车辆
     */
    @Transactional
    @Override
    public Result assign(DeviceStaticVO deviceStaticVO) {
        Integer agentId = deviceStaticVO.getAgentId();
        List<String> devSNList = Arrays.asList(deviceStaticVO.getDevSNList().split(","));
        Integer type = deviceStaticVO.getType();
        List<DevDeviceStaticDO> dodList = super.selectByMap(ImmutableMap.of("devSNList", devSNList));
        for (DevDeviceStaticDO dsd : dodList) {
            dsd.setAgentId(agentId);
            if (type != null && type == 2) { // 分配客户
                String saleArea = deviceStaticVO.getSaleArea();
                String saleCountry = deviceStaticVO.getSaleCountry();
                Date sendTime = deviceStaticVO.getSendTime();
                // Assert.isTrue(StringUtils.isNotBlank(saleArea), "销售区域不能是空");
                Assert.isTrue(StringUtils.isNotBlank(saleCountry + saleArea), "销售区域不能是空");
                Assert.isTrue(sendTime != null, "发货时间不能是空");
                dsd.setSendTime(sendTime);
                dsd.setSaleCity(saleArea);
                dsd.setSaleCountry(saleCountry);
                dsd.setSendTime(sendTime);
                dsd.setStatus(0);
            }
            int i = this.update(dsd);
            if (i == 0) {
                if (type != null && type == 2) { // 分配客户
                    throw new BizException(-1, "序列号=" + dsd.getDevSn() + "分配失败, 请检查发货时间是否大于入库时间");
                } else {
                    throw new BizException(-1, "过户失败");
                }
            }
        }
        return Result.ok();
    }

    @Override
    public List<VehicleDetailVO> selectListByUnAllot(DeviceListQO qo) {
        return devDeviceStaticMapper.selectListByUnAllot(qo);
    }

    // 充满电10个小时 即600分钟
    private final Integer longFull = 600;

    @Override
    public DevDeviceStaticDO selectByDriverId(Integer driverId) {
        return devDeviceStaticMapper.selectByDriverId(driverId);
    }

    @Override
    public List<DeviceListVO> selectList(DevListQO qo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<DevCarDO> listDevCarDO = devCarMapper.selectPage(null);
        Map<Object, Object> carMap = new HashMap<>();
        for (DevCarDO car : listDevCarDO) {
            carMap.put(car.getId(), car.getLife());
        }
        List<DevFollowDO> listDevFollowDO = devFollowMapper.selectPage(null);
        List<Integer> listFollow = new ArrayList<>();
        for (DevFollowDO follow : listDevFollowDO) {
            listFollow.add(follow.getDevId());
        }
        List<DeviceListVO> listVO = new ArrayList<>();
        List<DeviceListDO> list = devDeviceStaticMapper.selectByAgentId(qo);
        Map<String, Object> map = new HashMap<>();
        for (DeviceListDO listDO : list) {
            DeviceListVO vo = new DeviceListVO();
            listDO.setBattery(listDO.getBattery() == null ? 0 : listDO.getBattery());
            Integer haveKM = Integer.valueOf(carMap.get(listDO.getCarId()).toString()) * listDO.getBattery() / 100 - 5;
            vo.setDevId(listDO.getDevId());
            vo.setCarNo(listDO.getCarNo());
            vo.setCarNickname(listDO.getCarNickname());
            vo.setDeviceStatus(listDO.getDeviceStatus());
            vo.setBattery(listDO.getBattery());
            vo.setHaveKM(haveKM <= 0 ? 0 : haveKM);
            vo.setLastUpTime(listDO.getLastUpTime() == null ? null : sdf.format(listDO.getLastUpTime()));
            vo.setSpeed(listDO.getSpeed());
            vo.setIsFollow(listFollow.contains(listDO.getDevId()) ? 1 : 0);
            vo.setAddress(listDO.getAddress());
            vo.setTotalKM(listDO.getTotalKM());
            vo.setLongIsFull((100 - listDO.getBattery()) * longFull / 100);
            vo.setLat(listDO.getLat());
            vo.setLng(listDO.getLng());
            vo.setToDir(listDO.getToDir());
            map.put("devId", listDO.getDevId());
            map.put("endTime", null);
            // SysDriverUseLogDO useLog =
            // sysDriverUseLogMapper.selectInUse(map);
            // if (useLog != null) {
            // vo.setDriverId(useLog.getDriverId());
            // SysDriverInfoDO info =
            // sysDriverInfoMapper.selectById(useLog.getDriverId());
            // if (info != null) {
            // vo.setDriverName(info.getName());
            // vo.setHeadPic(info.getHeadPic());
            // }
            // }
            listVO.add(vo);
        }
        return listVO;
    }

    @Override
    public int selectCountList(DevListQO qo) {
        return devDeviceStaticMapper.selectCountByAgentId(qo);
    }

    // @Override
    // public DeviceDetailsVO details(Integer devId) {
    // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // DevDeviceStaticDO devStatic = devDeviceStaticMapper.selectById(devId);
    // DevDeviceOnlineDO devOnline =
    // devDeviceOnlineMapper.selectOne(ImmutableMap.of("devId", devId));
    // if (devStatic != null && devOnline != null) {
    // SysAgentDO agent = sysAgentMapper.selectById(devStatic.getAgentId());
    // DeviceDetailsVO ddv = new DeviceDetailsVO();
    // DevCarDO car = devCarMapper.selectById(devStatic.getCarId());
    // ddv.setCarNo(devStatic.getCarNo());
    // ddv.setDeviceStatus(devOnline.getDeviceStatus());
    // ddv.setBattery(devOnline.getBattery());
    // ddv.setHaveKM((car.getLife() * devOnline.getBattery() - 5) + "");
    // ddv.setLastUpTime(sdf.format(devOnline.getLastUpTime()));
    // ddv.setSpeed(devOnline.getSpeed());
    // ddv.setTotalKM(devOnline.getFarAway());
    // ddv.setAddress(devOnline.getCity() + devOnline.getAddress());
    // ddv.setCarNickname(devStatic.getCarNickName());
    // ddv.setTeam(agent != null ? agent.getCompany() : null);
    // ddv.setCarNub(devStatic.getVin());
    // int count = devFollowMapper.selectCount(ImmutableMap.of("devId",
    // devStatic.getDevId()));
    // ddv.setIsFollow(count == 0 ? 0 : 1);
    // ddv.setLat(devOnline.getLat());
    // ddv.setLng(devOnline.getLng());
    // ddv.setToDir(devOnline.getToDir());
    // ddv.setDevId(devId);
    // ddv.setDoor(devOnline.getDoor());
    // ddv.setLongIsFull((100 - devOnline.getBattery()) * longFull / 100);
    // DevRunDO run = devRunMapper.selectOne(ImmutableMap.of("imei",
    // devStatic.getImei()));
    // ddv.setStopTime(run == null ? null : (run.getEndTime() == null ? null :
    // sdf.format(run.getEndTime())));
    // run = devRunMapper.selectHundredLoss(ImmutableMap.of("imei",
    // devStatic.getImei()));
    // if (run != null) {
    // ddv.setHundredLoss(run.getRunAWay() < 0.01 ? "13.1"
    // : String.format("%.1f", run.getRunABattery() / 100 * 26 * 100 /
    // run.getRunAWay()));
    // }
    // return ddv;
    // }
    // return null;
    // }
    @Override
    public DeviceDataCountVO dataCount(String agentPath) {
        DeviceDataCountVO vo = new DeviceDataCountVO();
        Map<String, Object> map = new HashMap<>();
        map.put("agentPath", agentPath);
        map.put("deviceStatus", null);
        vo.setAll(devDeviceStaticMapper.selectCountByAgentPathAndDeviceStatus(map));
        map.put("deviceStatus", 2);
        int running = devDeviceStaticMapper.selectCountByAgentPathAndDeviceStatus(map);
        map.put("deviceStatus", 4);
        int start = devDeviceStaticMapper.selectCountByAgentPathAndDeviceStatus(map);
        vo.setStartUp(running + start);
        map.put("deviceStatus", 5);
        vo.setFlameout(devDeviceStaticMapper.selectCountByAgentPathAndDeviceStatus(map));
        map.put("deviceStatus", 3);
        vo.setCharge(devDeviceStaticMapper.selectCountByAgentPathAndDeviceStatus(map));
        map.put("deviceStatus", 0);
        vo.setMatter(devDeviceStaticMapper.selectCountByAgentPathAndDeviceStatus(map));
        return vo;
    }

    /**
     * 车辆列表（地图筛选）
     */
    @Override
    public List<DeviceCarListMapVO> showCarList(DeviceCarListMapQO qo) {
        qo.setAgentPath(sysAgentService.agentIdConvertAgentPath(qo.getAgentId()));
        List<DeviceCarListMapVO> carList = devDeviceStaticMapper.selectCarList(qo);
        List<DeviceCarListMapVO> vo = ConvertorUtils.deepConvertList(carList, DeviceCarListMapVO.class);
        return vo;
    }

    @Override
    public int countCarList(DeviceCarListMapQO qo) {
        return devDeviceStaticMapper.countCarList(qo);
    }
    // @Override
    // public Result open(Integer devId, String lat, String lng) {
    // DevDeviceStaticDO staticDO = devDeviceStaticMapper.selectById(devId);
    // if (staticDO != null) {
    // DevDeviceOnlineDO online =
    // devDeviceOnlineMapper.selectOne(ImmutableMap.of("devId",
    // staticDO.getDevId()));
    // if (online.getDeviceStatus() != null &&
    // online.getDeviceStatus().equals(0)) {
    // return Result.error(MessageUtil.ERROR,
    // MessageUtil.getMsg("The vehicle has been Off-line and cannot be
    // Unloacked"));
    // }
    // if (online.getFire() == 1) {
    // return Result.error(MessageUtil.ERROR,
    // MessageUtil.getMsg("The vehicle has been activated and cannot be
    // Unloacked"));
    // }
    // if (StringUtils.isNoneBlank(lat, lng)) {
    // Double d = GPSPoint.getDistance(Double.valueOf(online.getLng()),
    // Double.valueOf(online.getLat()),
    // Double.valueOf(lng), Double.valueOf(lat));
    // if (d > 1000) {
    // return Result.error(MessageUtil.ERROR,
    // MessageUtil.getMsg("The vehicle has been activated and cannot be
    // Unloacked"));
    // }
    // }
    // String upid = String.valueOf(((int) ((Math.random() * 9 + 1) * 100000)));
    // String command = "<C006," + staticDO.getImei() + "," + upid +
    // ",1002,1003>";// 1002,1003
    // String result = SocketUtil.GetInstance().SendMsg(command,
    // online.getIpPort());
    // if (result.equals("success")) {
    // // TODO 插入一次操作记录
    // return Result.ok(result);
    // } else {
    // return Result.error("命令执行失败，请重试");
    // }
    // }
    // return Result.ok();
    // }
    // @Override
    // public Result close(Integer devId) {
    // DevDeviceStaticDO staticDO = devDeviceStaticMapper.selectById(devId);
    // if (staticDO != null) {
    // DevDeviceOnlineDO online =
    // devDeviceOnlineMapper.selectOne(ImmutableMap.of("devId",
    // staticDO.getDevId()));
    // if (online.getFire() == 1) {
    // return Result.error(MessageUtil.ERROR,
    // MessageUtil.getMsg("The vehicle has been activated and cannot be
    // locked"));
    // }
    // if (online.getDoor() != 6) {
    // return Result.error(MessageUtil.ERROR,
    // MessageUtil.getMsg("The door is open. Please confirm that the door is
    // closed and try again"));
    // }
    // String upid = String.valueOf(((int) ((Math.random() * 9 + 1) * 100000)));
    // String command = "<C006," + staticDO.getImei() + "," + upid + ",1001>";//
    // 1001,1004
    // String result = SocketUtil.GetInstance().SendMsg(command,
    // online.getIpPort());
    // if (result.equals("success")) {
    // // TODO 插入一次操作记录 是否devId
    // DevOperateDO model = new DevOperateDO();
    // model.setCommand(command);
    // // model.setCarNub(dsd.getCarNub());
    // // model.setImei(dsd.getImei());
    // model.setInfo("开锁");
    // model.setUpIndex(upid);
    // // model.setCity(dod.getCity());
    // model.setStatus("已发送到连接池");
    // model.setCreateTime(new Date());
    // devOperateMapper.insert(model);
    // return Result.ok(result);
    // } else {
    // return Result.error("命令执行失败，请重试");
    // }
    // }
    // return Result.ok();
    // }
}
